#include <atomic>
#include <chrono>
#include <string>
#include <thread>
#include <vector>
#define private public
#include "async_logger.h"
#undef private
#include "console_output_strategy.h"
#include "gtest/gtest.h"

namespace Base {
namespace SystemLog {
namespace {
constexpr size_t TEST_BUFFER_SIZE = 1024 * 1024; // 1MB
} // namespace

class LoggerConcurrentStressTest : public testing::Test {
public:
    static void SetUpTestCase(void) {}
    static void TearDownTestCase(void) {}
    void SetUp() override {
        // 每个测试前确保日志器处于干净状态
        auto& logger = AsyncLogger<TEST_BUFFER_SIZE>::GetInstance();
        if (logger.running_.load()) {
            logger.Stop();
        }
    }
    void TearDown() override {
        // 每个测试后停止日志器
        auto& logger = AsyncLogger<TEST_BUFFER_SIZE>::GetInstance();
        if (logger.running_.load()) {
            logger.Stop();
        }
    }
};

/**
 * @tc.name: LoggerConcurrentStressTest_001
 * @tc.desc: verify concurrent stress testing of AsyncLogger
 * @tc.type: PERF
 */
TEST_F(LoggerConcurrentStressTest, LoggerConcurrentStressTest_001)
{
    auto& logger = AsyncLogger<TEST_BUFFER_SIZE>::GetInstance();
    
    // 不添加输出策略以避免测试中的噪音输出
    
    ASSERT_EQ(logger.Start(), ERR_OK);
    
    const int numThreads = 4;
    const int messagesPerThread = 10; // 减少消息数量
    std::vector<std::thread> threads;
    std::atomic<int> successCount{0};
    
    // 启动多个线程并发写入
    for (int t = 0; t < numThreads; ++t) {
        threads.emplace_back([&logger, &successCount, messagesPerThread, t]() {
            for (int i = 0; i < messagesPerThread; ++i) {
                std::string msg = "Thread " + std::to_string(t) + " message " + std::to_string(i) + "\n";
                if (logger.Append(msg.c_str(), msg.length()) == ERR_OK) {
                    successCount++;
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证所有消息都成功写入
    EXPECT_EQ(successCount.load(), static_cast<int>(numThreads * messagesPerThread));
    
    // 获取最终统计
    auto stats = logger.GetBufferStats();
    EXPECT_GT(stats.totalNodes, static_cast<size_t>(0));
    EXPECT_GT(stats.memoryUsage, static_cast<size_t>(0));
    
    logger.Stop();
}

} // namespace SystemLog
} // namespace Base
